<template>
  <el-container>
    <el-header style="display: flex; justify-content: space-between; align-items: center;">
      <h1>用户列表</h1>
      <el-button type="primary" @click="goToAddUser">添加用户</el-button>
    </el-header>
    <el-main>
      <el-table :data="users" style="width: 100%">
        <el-table-column prop="id" label="ID" width="100" />
        <el-table-column prop="username" label="用户名" />
        <el-table-column prop="roleId" label="角色ID" />
        <el-table-column label="操作" width="200">
          <template #default="scope">
            <el-button type="primary" size="small" @click="editUser(scope.row)">编辑</el-button>
            <el-button type="danger" size="small" @click="deleteUser(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-main>
  </el-container>
</template>

<script>
import { mapState, mapActions } from 'vuex';

export default {
  computed: {
    ...mapState(['users']),
  },
  methods: {
    ...mapActions(['fetchUsers']),
    goToAddUser() {
      this.$router.push('/users/add');
    },
    editUser(user) {
      this.$router.push(`/users/edit/${user.id}`);
    },
    async deleteUser(id) {
      await this.$api.deleteUser(id);
      this.fetchUsers();
    },
  },
  mounted() {
    this.fetchUsers();
  },
};
</script>